<?php

namespace Home\Controller;

use Think\Controller;
use Org\Util\Juhe;
/**
 * 立即支付
 * @author Scor
 * @copyright 2015/09/28
 */
class BuyNowController extends HomeController {
    public function add(){
        if (session('userphone')){
            $userid = session('userid');
            $map["status"]=2;
            $map["uid"]=$userid;
            $cartTable= D('cart');
            $res2=$cartTable->where($map)->delete();
            $data['pid']=I("id");
            $data["pnum"]=1;
            $data["uid"]=$userid;
            $data["status"]=2;
            $res=M('cart')->add($data);
            $this->redirect('BuyNow/index',array('id'=>$data['pid']));
        }else {
            $this->redirect('User/edit');
        }

    }
    /**
     *该方法实现直接购买功能
     * 不同于购物车：该方法没有从mysql中获取数据，数据来源是post参数请求
     * 同于购物车：需要修改、判断库存，需要判断是否参与活动
     *
     */
    public function index(){
        $userid = session('userid');
        $map2['id']=$userid;
        $cartPro = D('product');
        $cartAddress = D('addr');
        $sqlpro = "select a.pid,a.pnum,b.name,b.quantity,b.picurlarray,b.price,b.tagarray from gr_cart a,gr_product b where a.uid = $userid and "
            . "a.pid = b.id and a.status = 2";
        $cartPros = $cartPro->query($sqlpro);
        $sqladdress = "select * from gr_addr  where uid = $userid and status = 1";
        $cartAddresses = $cartAddress->query($sqladdress);
        //判断是否参加活动
        $activityMoreBuy=M('activity_more_buy');
        for ($i = 0; $i < count($cartPros); $i++) {
            $picarray = json_decode($cartPros[$i]['picurlarray']);
            $cartPros[$i]['pic'] = $picarray[0];
            $isActivity = $activityMoreBuy->where('id=' . $cartPros[$i]['pid'])->select();
            if(count($isActivity)>0){
                $oldprice =  $cartPros[$i]['price'];
                $price1 = $isActivity[0]['price1'];
                $price2 = $isActivity[0]['price2'];
                $num1 = $isActivity[0]['num1'];
                $num2 = $isActivity[0]['num2'];
                $cartPros[$i]['num0'] = "1-".($num1-1)."件:";//展示用
                $cartPros[$i]['num1'] = "≥".$num1."件:";//展示用
                $cartPros[$i]['price0'] ="￥".$oldprice;
                $cartPros[$i]['price1'] = "￥".$price1;
                if($price2>0 && $num2>0){
                    $cartPros[$i]['num2']="≥".$num2."件:";//展示用
                    $cartPros[$i]['price2']="￥".$price2;
                }else{
                    $cartPros[$i]['num2']="";//展示用
                    $cartPros[$i]['price2']="";
                }
                if($cartPros[$i]['pnum']>=$num1 && $num1>0 && $price1>0){
                    $cartPros[$i]['price']=$price1;
                    if($cartPros[$i]['pnum'] >= $num2 && $num2 > 0 &&$price2>0){
                        $cartPros[$i]['price']=$price2;
                    }
                }
            }else{
                $cartPros[$i]['num0'] = "暂无优惠";//展示用
                $cartPros[$i]['num1'] = "";//展示用
                $cartPros[$i]['price0'] = "";
                $cartPros[$i]['price1'] = "";
                $cartPros[$i]['num2']="";//展示用
                $cartPros[$i]['price2']="";
            }
        }
        //总价格
        $orderPrice=$cartPros[0]['price']*$cartPros[0]['pnum'];
        if(strstr($cartPros[0]['tagarray'],'SINGLE')) {
            $special=1;
        }
        $buyers=M("buyers")->where($map2)->find();
        $this->buyers=$buyers;
        $this->assign("orderPrice", $orderPrice);
        $this->assign("requriePrice", $orderPrice);
        $this->buynow=1;
        $this->assign('cartPros', $cartPros);
        $this->assign("proCount",count($cartPros));
        $this->assign('cartAddresses', $cartAddresses);
        $this->special=$special;
        $this->display("Index/cart");
    }
    public function checkStore(){
        $userid = session('userid');
        $flag = "";
        $prostable = M('product');
        $carttable = M('cart');
        $limitTable = M('product_limit');
        $cartPros = $carttable->where(array('uid'=>$userid,'status'=>2))->find();
        $pro = $prostable->where(array('id'=>$cartPros['pid']))->find();
        $cartNum=$carttable->where(array('uid'=>$userid,'pid'=>$cartPros['pid'],'status'=>2))->sum('pnum');
        $alreadyBuy=$limitTable->where(array('uid'=>$userid,'pid'=>$cartPros['pid'],'buyDate'=>date('Ymd',time())))->sum('cnt');
        if($pro['limit_num']==0){
        }elseif($pro['limit_num']<=$alreadyBuy){
            $flag.=$pro['name']."是限购商品，每天每人仅限购".$pro['limit_num']."件";
            $carttable->where(array('uid'=>$userid,'pid'=>$cartPros['pid']))->delete();
        }elseif($cartNum>($pro['limit_num']-$alreadyBuy)){
            $flag.= $pro['name']."是限购商品，你今天还能购买".($pro['limit_num']-$alreadyBuy)."件;";
            $data = array('pnum'=>($pro['limit_num']-$alreadyBuy));
            $carttable->where(array('uid'=>$userid,'pid'=>$cartPros['pid'],'status'=>2))->save($data);
        }

        if($pro['inventory']==0){
            $flag = $pro['name']."库存不足;";
        }else if ($pro['inventory'] < $cartPros['pnum']){
            $flag= $pro['name']."仅剩".$pro['inventory']."件;";
            $data = array('pnum'=>$pro['inventory']);
            $carttable->where(array('uid'=>$userid,'pid'=>$cartPros['pid'],'status'=>2))->save($data);
        }
        $this->ajaxReturn($flag);
    }
    /**
     * 创建订单
     */
    public function createOrder($addressradio = "", $remark = "",$amount="") {
        //清除立即购买商品
        $userid = session('userid');
        if($amount==""||$amount==null){
            $amount=0;
        }
        $orderNo = "O" .$userid.NOW_TIME;
        $smslist=":";
        $cartPro = D('product');
        $user_info=session('USER');
        if($user_info['contract_level']>0){
            $order_type=2;
            $sql="IF(b.contract_price='',b.price,b.contract_price) as price";
        }else{
            $order_type=1;
            $sql="b.price";
        }
        $sqlpro = "select a.pid,a.pnum,b.name,b.quantity,b.picurlarray,".$sql." from gr_cart a,gr_product b where a.uid = $userid and "
            . "a.pid = b.id and a.status = 1";
        $cartPros = $cartPro->query($sqlpro);
        $buyNowGoods=$cartPros[0];
        $protable = M('product');
        $orderGoods = M("order_goods");
        /**
         * 多买多优惠 start
         * @param pid
         * @author Scor
         */
        $isActivity = M('activity_more_buy')->where('id='.$buyNowGoods['pid'])->find();
        if(count($isActivity)>0){
            if($buyNowGoods['pnum']>=$isActivity['num1']){
                $buyNowGoods['price']=$isActivity['price1'];
            }
        }
        if (count($isActivity) > 0) {
            if ($buyNowGoods['pnum']>=$isActivity['num1']&&$isActivity['num1']>0&&$isActivity['price1']>0) {
                $buyNowGoods['price'] = $isActivity['price1'];
                if($buyNowGoods['pnum']>=$isActivity['num2']&&$isActivity['num2']>0&&$isActivity['price2']>0){
                    $buyNowGoods['price'] = $isActivity['price2'];
                }
            }
        }
        /**
         * 多买多优惠 end
         */
        $buyNowGoods['sumproprice'] = $buyNowGoods['pnum'] * $buyNowGoods['price'];
        $orderPrice =$buyNowGoods['pnum'] * $buyNowGoods['price'];
        $order_goods_data = array(
            'orderid' => $orderNo,
            'pid' => $buyNowGoods['pid'],
            'price' => $buyNowGoods['price'],
            'cartnum' => $buyNowGoods['pnum'],
            'expectcartnum' => $buyNowGoods['pnum'],
            'totalprice' => $buyNowGoods['sumproprice'],
            'expecttotalprice' => $buyNowGoods['sumproprice']
        );
        $smslist=$smslist.get_goods_name($buyNowGoods['pid'])."*".$buyNowGoods['pnum'].'个/';
        $orderGoods->add($order_goods_data);
        $product = $protable->where(array('id'=>$buyNowGoods['pid']))->find();
        $proInventory = $product['inventory']-$buyNowGoods['pnum'];
        $proData = array('inventory'=>$proInventory);
        $protable->where(array('id'=>$buyNowGoods['pid']))->save($proData);
        $limitTable = M("product_limit");
        if($product['limit_num']>0) {
            $limitDataList = array(
                'uid' => $userid,
                'pid' => $buyNowGoods['pid'],
                'cnt' => $buyNowGoods['pnum'],
                'buyDate' => date('Ymd', NOW_TIME),
                'createAt' => NOW_TIME,
                'updateAt' => NOW_TIME,
                'orderid' => $orderNo
            );
            $limitTable->addA($limitDataList);
        }
        $addr = M('addr')->where(array('id' => $addressradio, 'status' => 1))->find();
        $orderData = array(
            'orderid' => $orderNo,
            'order_type'=>$order_type,
            'amount' => $orderPrice,
            'expectamount' => $orderPrice,
            'uid' => $userid,
            'createDate' => NOW_TIME,
            'toName' => $addr['name'],
            'toProvince' => $addr['province'],
            'toCity' => $addr['city'],
            'toArea' => $addr['area'],
            'toStreet' => $addr['street'],
            'toPhone' => $addr['phone'],
            'remark' => $remark,
            'lastupdate' => NOW_TIME,
            'toShopName' => $addr['shopname']
        );
        if($buyNowGoods["price"]<=0){
            $orderData['amount']=0;
            $orderData['status']=4000;
        }else{
            $amountData['id']=$userid;
            D("buyers")->where(array('id'=>$userid))->setDec('amount',$amount);
            $orderData['useamount']=$amount;
            $orderData['amount']=$orderPrice-$amount;
        }
        if(count($cartPros)>0){
            M("order")->add($orderData);
            M('cart')->where(array('uid'=>session('userid')))->delete();
        }
        $this->redirect('Center/history');
    }
}
